import { CLEARLANDMARK, UPDATELANDMARK } from '../types/landmark'
import { handleActions } from 'redux-actions'
import { getStorageSync, setStorageSync } from '../../crossplatform/apiservice/storage'
import { insertCityHistoryRequest } from '../../service/city-controller'

const Schema = {
  lng: '',
  lat: '',
  landmarkName: ''
}

const getCatchTime = () => {
  const landmark = getStorageSync('landmark')
  let CacheTime = landmark && landmark.CacheTime
  if (!CacheTime) {
    let oDate = new Date()
    oDate.setDate(oDate.getDate() + 7)
    CacheTime = oDate.getTime()
  }
  return CacheTime
}

export default handleActions(
  {
    [UPDATELANDMARK](state, action) {
      let newState = {
        ...state,
        ...action.payload
      }

      if (newState.landmarkName) {
        insertCityHistoryRequest({ cityName: newState.landmarkName })
      }

      setStorageSync('landmark', { ...newState, CacheTime: getCatchTime() })

      return {
        ...newState
      }
    },
    [CLEARLANDMARK](state, action) {
      let newState = {
        lng: '',
        lat: '',
        landmarkName: ''
      }
      setStorageSync('landmark', {})

      return {
        ...newState
      }
    }
  },
  Schema
)
